package com.linemanage.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class DecodeZh implements Filter {

	private String charset;

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 1. ServletRequest 转成 HttpServletRequest
		HttpServletRequest req = (HttpServletRequest) request;
		response.setCharacterEncoding(charset);
		// 2. 如果是GET，就生成一个Wrapper对象，覆盖获取参数的方法进行转码
		if ("GET".equalsIgnoreCase(req.getMethod())) {
			req = new MyRequest(req,charset);
		}
		// 3. 如果是POST，request.setCharacterEncoding("UTF-8")
		else if ("POST".equalsIgnoreCase(req.getMethod())) {
			req.setCharacterEncoding(charset);
		}
		// 4.调用chain.doFilter继续向后执行
		chain.doFilter(req, response);
	}

	public void init(FilterConfig config) throws ServletException {
		//从web.xml传入指定的字符编码，如果没有指定charset,则默认用utf-8
		this.charset=config.getInitParameter("charset");
		if(this.charset==null){
			this.charset="utf-8";
		}
	}

}

	/**
		 * 包装器，覆盖 getParameter()和 getParameterValues() 这两个方法来进行转码。
		 * @author BeanSoft
		 *
		 */
class MyRequest extends HttpServletRequestWrapper {

	private String charset;
	public MyRequest(HttpServletRequest request,String charset) {
		super(request);
		this.charset=charset;
		// TODO Auto-generated constructor stub
	}

	/**
	 * 字符串转码。
	 * 
	 * @param input
	 *            输入字符串
	 * @param srcEncoding
	 *            源字符串的编码
	 * @param targetEncoding
	 *            目标编码
	 * @return 转换过的内容
	 */
	private String changeEncoding(String input, String srcEncoding,
			String targetEncoding) {
		try {
			// 1. 获取源编码的bytes[]
			byte[] data = input.getBytes(srcEncoding);
			// 2. 将bytes[]按照制定编码转换为String
			return new String(data, targetEncoding);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return input;
	}

	@Override
	public String getParameter(String name) {
		String value = super.getParameter(name);

		if (value != null) {
			value = changeEncoding(value, "ISO8859-1", charset);
		}
		return value;
	}

	@Override
	public String[] getParameterValues(String name) {
		String[] values = super.getParameterValues(name);
		if (values != null && values.length > 0) {
			for (int i = 0; i < values.length; i++) {
				String value = values[i];

				values[i] = changeEncoding(value, "ISO8859-1", charset);
			}
		}
		return values;
	}

}
